﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Pantry.Business;
using Pantry.Commons;
using Pantry.Entity;

namespace Pantry.Web.Users
{
    public partial class EditContactForm : System.Web.UI.Page
    {
        private ContactBus _contactBus;
        private Contact _contact;
        private DataView _dataView;
        private static bool _isSort = true;
        private readonly IFormatProvider _formatProvider = CultureInfo.CurrentCulture;
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if(!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    BindToListContactMethod();
                    BindToListContactType();
                    int contactId = int.Parse(Request.QueryString["id"], _formatProvider);
                    _contactBus = new ContactBus();
                    _contact = new Contact();
                    _contact = _contactBus.ContactObjectById(contactId);
                    TextBoxFirstName.Text = _contact.FirstName;
                    TextBoxSurname.Text = _contact.Surname;
                    TextBoxKnownAs.Text = _contact.KnownAs;
                    TextBoxOfficePhone.Text = _contact.OfficePhone;
                    TextBoxMobilePhone.Text = _contact.MobilePhone;
                    TextBoxHomePhone.Text = _contact.HomePhone;
                    TextBoxManagerName.Text = ManagerNameById(_contact.ManagerId);
                    HiddenManagerId.Value = _contact.ManagerId.ToString(_formatProvider);
                    ListContactType.SelectedValue = _contact.ContactType.ToString(_formatProvider);
                    ListContactMethod.SelectedValue = _contact.BestContactMethod.ToString(_formatProvider);
                    TextBoxEmail.Text = _contact.Email;
                    TextBoxJobRole.Text = _contact.JobRole;
                    TextBoxWorkBase.Text = _contact.WorkBase;
                    TextBoxJobTitle.Text = _contact.JobTitle;
                    CheckBoxIsActive.Checked = _contact.IsActive;
                }
                else
                {
                    Response.Redirect("~/Users/ViewListContact.aspx");
                }
            }
            FilterContact(TextBoxFirstNameSearch.Text, TextBoxSurnameSearch.Text, CheckBoxIncludeInactive.Checked);
            
        }
        #region Method

        private void FilterContact(string firstName, string surName, bool isIncludeInactiveContact)
        {
            try
            {
                _contactBus = new ContactBus();
                DataTable dataTable = _contactBus.ListContact();
                _dataView = dataTable.DefaultView;
                string statement = string.Format(_formatProvider, "FullName like '%{0}%' AND FullName LIKE '%{1}%'", firstName, surName);
                if (!isIncludeInactiveContact)
                {
                    statement += "AND IsActive = 'true'";
                }
                _dataView.RowFilter = statement;
                CollectionPager1.PageSize = 5;
                CollectionPager1.BindToControl = RepeaterContact;
                CollectionPager1.DataSource = _dataView;
                RepeaterContact.DataSource = CollectionPager1.DataSourcePaged;
                RepeaterContact.DataBind();
            }
            catch (Exception exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
                throw;
            }
        }

        private void SortContact(string field)
        {
            try
            {
                if (_isSort)
                {
                    _dataView.Sort = string.Format(_formatProvider, "{0} DESC", field);
                    _isSort = false;
                }
                else
                {
                    _dataView.Sort = string.Format(_formatProvider, "{0} ASC", field);
                    _isSort = true;
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
                throw;
            }
        }

        private void BindToListContactType()
        {
            _contactBus = new ContactBus();
            DataTable dataTable = _contactBus.ListContactType();
            ListContactType.DataSource = dataTable.DefaultView;
            ListContactType.DataValueField = "ID";
            ListContactType.DataTextField = "ContactType";
            ListContactType.DataBind();
        }

        private void BindToListContactMethod()
        {
            _contactBus = new ContactBus();
            DataTable dataTable = _contactBus.ListBestContactMethod();
            ListContactMethod.DataSource = dataTable.DefaultView;
            ListContactMethod.DataValueField = "ID";
            ListContactMethod.DataTextField = "BestContactMethod";
            ListContactMethod.DataBind();
        }

        private string ManagerNameById(int managerId)
        {
            try
            {
                _contactBus = new ContactBus();
                return _contactBus.ManagerNameById(managerId);
            }
            catch (Exception exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
                throw;
            }
        }
       
        #endregion
        protected void ButtonSaveClick(Object sender, EventArgs e)
        {
            try
            {
                _contactBus = new ContactBus();
                _contact = new Contact
                {
                    ContactId = int.Parse(Request.QueryString["id"], CultureInfo.CurrentCulture),
                    FirstName = TextBoxFirstName.Text,
                    Surname = TextBoxSurname.Text,
                    KnownAs = TextBoxKnownAs.Text,
                    OfficePhone = TextBoxOfficePhone.Text,
                    MobilePhone = TextBoxMobilePhone.Text,
                    HomePhone = TextBoxHomePhone.Text,
                    Email = TextBoxEmail.Text,
                    ManagerId = int.Parse(HiddenManagerId.Value, CultureInfo.CurrentCulture),
                    ContactType = int.Parse(ListContactType.SelectedValue, _formatProvider),
                    BestContactMethod = int.Parse(ListContactMethod.SelectedValue, _formatProvider),
                    JobRole = TextBoxJobRole.Text,
                    WorkBase = TextBoxWorkBase.Text,
                    JobTitle = TextBoxJobTitle.Text,
                    IsActive = CheckBoxIsActive.Checked
                };
                bool result = _contactBus.UpdateContact(_contact);
                UpdateLabel.Text = result ? "This contact has been updated successfully!" : "There is a error!";
                Response.Redirect("ViewListContact.aspx");
            }
            catch (Exception exception)
            {
                UpdateLabel.Text = exception.Message;
                ExceptionHandler.WriteErrorLog(exception);
                throw;
            }
        }
        protected void ButtonLookupClick(object sender, EventArgs e)
        {
            PanelPopup.Visible = true;
            PanelPopup.CssClass = "popup-container";
            FilterContact(TextBoxFirstNameSearch.Text, TextBoxSurnameSearch.Text, CheckBoxIncludeInactive.Checked);
        }
        protected void ButtonBackClick(object sender, EventArgs e)
        {
            Response.Redirect("~/Users/ViewListContact.aspx");
        }
        protected void ButtonSearchClick(object sender, EventArgs e)
        {
            FilterContact(TextBoxFirstNameSearch.Text, TextBoxSurnameSearch.Text, CheckBoxIncludeInactive.Checked);
        }
        protected void CheckBoxIncludeActiveCheckedChanged(object sender, EventArgs e)
        {
            FilterContact(TextBoxFirstNameSearch.Text, TextBoxSurnameSearch.Text, CheckBoxIncludeInactive.Checked);
        }
        protected void ButtonSelectClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(HttpHelper.GetFormString("RadioContactId")))
            {
                string[] contact = HttpHelper.GetFormString("RadioContactId").Split('$');
                TextBoxManagerName.Text = contact[1];
                HiddenManagerId.Value = contact[0];
                PanelPopup.Visible = false;
            }
            else
            {
                PanelPopup.Visible = false;
            }
        }
        protected void ButtonCloseClick(object sender, EventArgs e)
        {
            PanelPopup.Visible = false;
        }
        protected void ButtonSortByNameClick(object sender, EventArgs e)
        {
            SortContact("FullName");
        }
        protected void ButtonSortByMobileClick(object sender, EventArgs e)
        {
            SortContact("MobilePhone");
        }
        protected void ButtonSortByEmailClick(object sender, EventArgs e)
        {
            SortContact("Email");
        }
        protected void ButtonSortByStatusClick(object sender, EventArgs e)
        {
            SortContact("IsActive");
        }
        protected void ButtonSortByContactTypeClick(object sender, EventArgs e)
        {
            SortContact("ContactType");
        }
    }
}
